<template style="position: relative">
  <div id="container">
  </div>

  <div style="position: fixed;top: 0.1rem; ">
    <el-button

      type="primary"
      style="font-size: 0.7rem;width: 3rem; height: 1rem;"
      plain
      @click="changetraffic">交通路况
    </el-button>
    <input type="text" placeholder="地方名字" v-model="searchplace"
           id="tipinput"
           @keydown.enter="searchNear"
           style="font-size: 0.7rem;width: 9rem; height: 1rem;"
    >
    <el-button
      type="primary"
      style="font-size: 0.7rem;width: 3rem; height: 1rem;" @click="searchNear">附近
    </el-button>
    <el-button type="primary" style="font-size: 0.7rem;width: 3rem; height: 1rem" @click="startdaohang">导航</el-button>
      <el-button
      type="primary"
      style="font-size: 0.7rem;width: 3rem; height: 2rem;" @click="change3D">3D
    </el-button>
    <!--查询列表,高德地图api绑定id-->
    <div id="panel" style="width: 30%; height:30%;overflow:auto"></div>
    <div id="panel1"></div>
    <van-popup v-model:show="show" position="bottom" :style="{ height: '30%',width:'100%',margin:'0 auto'}">
      <div
      style="
      text-align: center;
      line-height: 2rem;
     "
      >你确定你要去 <span style="color:#00b0b7">{{ ss }}</span> 吗</div>


      <button

style="font-size: 0.7rem;width:80%; height: 2rem; border: none;
 color: white;
 margin-top: 1rem;
 border-radius: 5rem;
margin-left: 2rem;
 font-size: 25px;
 background:#00b0b7"        @click="ssdaohang">导航</button>
    </van-popup>
  </div>

</template>

<script setup>
import {onMounted, reactive, ref, watch} from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'

const mapApiKey = reactive({
  securityJsCode: '88ac9a74c267fc9cd991c643f1a6c525', // 注意如果需要 2.0 mapApiKey.securityJsCode 必填
  key: 'e97857d242d439faa32287a728be2cbe' // 申请好的Web端开发者Key，首次调用 load 时必填
  // securityJsCode: '1cd0edac0a3ac0ab84cf2550cd3b5745',
  // key: '11c63682a43854ea78e47d02efcee939',
  //  securityJsCode: '227532164ea7dbc2180e469f5cbd83e8',
  // key: '06262f52d33628615b839c4b1b000ff3'
})
const show = ref(false);
const showPopup = () => {
  show.value = true;
};
const is3D=ref(true)
const change3D=()=>{
  is3D.value=!is3D.value
  initMap()
}
const ismaptraffic = ref(false)
const searchplace = ref('')
const nownowplace = ref('115.482337,38.814462')
const searchlnt1 = ref('')
const searchlnt = ref('')
const searchlat1 = ref('')
const searchlat = ref('')
let AMap = null
const ss = ref('')

const changetraffic = () => {
  ismaptraffic.value = !ismaptraffic.value
  initMap()
}

// 为了安全性，需要加密钥
window._AMapSecurityConfig = {
  securityJsCode: mapApiKey.securityJsCode
}

AMapLoader.load({
  'key': mapApiKey.key, // Web端 (JSAPI) key，首次调用load必填
  'version': '2.0' // JSAPI版本，默认 1.4.15
  // "plugins": ["AMap.Geolocation", "AMap.PlaceSearch"], // 要使用的插件列表
}).then((map) => {
  AMap = map
  initMap()
  searchNear()
}).catch((e) => {
  // 高德地图加载失败
  console.error(e)
})
const initMap = () => {
  if(is3D.value){
    // console.log(is3D.value)
    let map = new AMap.Map('container', {
    center: [116.857461, 39.310582], // 地图中心点坐标
    zoom: 15, // 地图缩放级别
    viewMode: '2D' // 使用3D视图'
    // pitch: 75, // 地图俯仰角度，默认0，取值范围0-83
  })
    if (ismaptraffic.value) {
    AMap.plugin(['AMap.TileLayer.Traffic'], function () {
       var trafficLayer = new AMap.TileLayer.Traffic({
        zIndex: 10
    });

    trafficLayer.setMap(map);
   trafficLayer.show(); // 显示路况图层
    })

  }else{
     AMap.plugin(['AMap.TileLayer.Traffic'], function () {
       var trafficLayer = new AMap.TileLayer.Traffic({
        zIndex: 10
    });

    trafficLayer.setMap(map);
    trafficLayer.hide(); // 显示路况图层
       })
  }


  map.on('click', function (e) {
    var position = [e.lnglat.lng, e.lnglat.lat]
    var infoWindow = new AMap.InfoWindow({
      anchor: 'top-left',
      content: '经纬度' + e.lnglat.lng + ',' + e.lnglat.lat
    });

    infoWindow.open(map, position);
    new AMap.Marker({position: position, map}); // 创建一个 Marker 实例
  })

  // 当前定位
  var options = {
    'showButton': true,//是否显示定位按钮
    'position': 'LB',//定位按钮的位置
    /* LT LB RT RB */
    'offset': [10, 20],//定位按钮距离对应角落的距离
    'showMarker': true,//是否显示定位点
    'markerOptions': {//自定义定位点样式，同Marker的Options
      'offset': new AMap.Pixel(-18, -36),
      'content': '<img src="https://a.amap.com/jsapi_demos/static/resource/img/user.png" style="width:36px;height:36px"/>'
    },
    'showCircle': true,//是否显示定位精度圈
    'circleOptions': {//定位精度圈的样式
      'strokeColor': '#0093FF',
      'noSelect': true,
      'strokeOpacity': 0.5,
      'strokeWeight': 1,
      'fillColor': '#02B0FF',
      'fillOpacity': 0.25
    }
  }
  AMap.plugin('AMap.Geolocation', function () {
    var geolocation = new AMap.Geolocation(options)
    map.addControl(geolocation)
    geolocation.getCurrentPosition()
  })

  var autoOptions = {
    input: 'tipinput'
  }

  AMap.plugin(['AMap.PlaceSearch', 'AMap.AutoComplete'], function () {
    var auto = new AMap.AutoComplete(autoOptions)
    var placeSearch = new AMap.PlaceSearch({
      city: '', // 兴趣点城市
      citylimit: true,  //是否强制限制在设置的城市内搜索
      pageSize: 10, // 单页显示结果条数
      children: 0, //不展示子节点数据
      pageIndex: 1, //页码
      extensions: 'all' //返回基本地址信息
    });


    auto.on('select', select)//注册监听，当选中某条记录时会触发
    function select(e) {
      // console.log(e)
      searchlnt.value = e.poi.location.lng //维度
      searchlat.value = e.poi.location.lat //经度
      placeSearch.setCity(e.poi.adcode)
      placeSearch.search(e.poi.name)  //关键字查询查询


      var lnglat = new AMap.LngLat(Number(searchlnt.value), Number(searchlat.value));
      // console.log(lnglat)
      var map = new AMap.Map("container", {
        resizeEnable: true,
        center: [lnglat.lat, lnglat.lng],

      })

      //详情查询
      placeSearch.getDetails(e.poi.id, function (status, result) {
        if (status === 'complete' && result.info === 'OK') {
          placeSearch_CallBack(result);
        }
      });
      var infoWindow = new AMap.InfoWindow({
        autoMove: true,
        offset: {x: 0, y: -30}
      });

      //回调函数
      function placeSearch_CallBack(data) {
        // console.log(data)
        var poiArr = data.poiList.pois;
        //添加marker
        var marker = new AMap.Marker({
          map: map,
          position: poiArr[0].location
        });
        map.setCenter(marker.getPosition());
        infoWindow.setContent(createContent(poiArr[0]));
        infoWindow.open(map, marker.getPosition());
      }

      function createContent(poi) {  //信息窗体内容
        var s = [];
        s.push("<b>名称：" + poi.name + "</b>");
        s.push("地址：" + poi.address);
        s.push("电话：" + poi.tel);
        s.push("类型：" + poi.type);
        return s.join("<br>");
      }

    }
  })

  }else{
   let  map = new AMap.Map('container', {
    resizeEnable: true,
    rotateEnable:true,
    pitchEnable:true,
    zoom: 17,
    pitch:80,
    rotation:-15,
    viewMode:'3D',//开启3D视图,默认为关闭
    buildingAnimation:true,//楼块出现是否带动画

    expandZoomRange:true,
    zooms:[3,20],
   center: [116.857461, 39.310582], // 地图中心点坐标
  });

  map.addControl(new AMap.ControlBar({
    showZoomBar:false,
    showControlButton:true,
    position:{
      right:'10px',
      top:'10px'
    }
  }))
    if (ismaptraffic.value) {
    AMap.plugin(['AMap.TileLayer.Traffic'], function () {
       var trafficLayer = new AMap.TileLayer.Traffic({
        zIndex: 10
    });

    trafficLayer.setMap(map);
   trafficLayer.show(); // 显示路况图层
    })

  }else{
     AMap.plugin(['AMap.TileLayer.Traffic'], function () {
       var trafficLayer = new AMap.TileLayer.Traffic({
        zIndex: 10
    });

    trafficLayer.setMap(map);
    trafficLayer.hide(); // 显示路况图层
       })
  }


  map.on('click', function (e) {
    var position = [e.lnglat.lng, e.lnglat.lat]
    var infoWindow = new AMap.InfoWindow({
      anchor: 'top-left',
      content: '经纬度' + e.lnglat.lng + ',' + e.lnglat.lat
    });

    infoWindow.open(map, position);
    new AMap.Marker({position: position, map}); // 创建一个 Marker 实例
  })

  // 当前定位
  var options = {
    'showButton': true,//是否显示定位按钮
    'position': 'LB',//定位按钮的位置
    /* LT LB RT RB */
    'offset': [10, 20],//定位按钮距离对应角落的距离
    'showMarker': true,//是否显示定位点
    'markerOptions': {//自定义定位点样式，同Marker的Options
      'offset': new AMap.Pixel(-18, -36),
      'content': '<img src="https://a.amap.com/jsapi_demos/static/resource/img/user.png" style="width:36px;height:36px"/>'
    },
    'showCircle': true,//是否显示定位精度圈
    'circleOptions': {//定位精度圈的样式
      'strokeColor': '#0093FF',
      'noSelect': true,
      'strokeOpacity': 0.5,
      'strokeWeight': 1,
      'fillColor': '#02B0FF',
      'fillOpacity': 0.25
    }
  }
  AMap.plugin('AMap.Geolocation', function () {
    var geolocation = new AMap.Geolocation(options)
    map.addControl(geolocation)
    geolocation.getCurrentPosition()
  })

  var autoOptions = {
    input: 'tipinput'
  }

  AMap.plugin(['AMap.PlaceSearch', 'AMap.AutoComplete'], function () {
    var auto = new AMap.AutoComplete(autoOptions)
    var placeSearch = new AMap.PlaceSearch({
      city: '', // 兴趣点城市
      citylimit: true,  //是否强制限制在设置的城市内搜索
      pageSize: 10, // 单页显示结果条数
      children: 0, //不展示子节点数据
      pageIndex: 1, //页码
      extensions: 'all' //返回基本地址信息
    });


    auto.on('select', select)//注册监听，当选中某条记录时会触发
    function select(e) {
      // console.log(e)
      searchlnt.value = e.poi.location.lng //维度
      searchlat.value = e.poi.location.lat //经度
      placeSearch.setCity(e.poi.adcode)
      placeSearch.search(e.poi.name)  //关键字查询查询


      var lnglat = new AMap.LngLat(Number(searchlnt.value), Number(searchlat.value));
      // console.log(lnglat)
      var map = new AMap.Map("container", {
        resizeEnable: true,
        center: [lnglat.lat, lnglat.lng],

      })

      //详情查询
      placeSearch.getDetails(e.poi.id, function (status, result) {
        if (status === 'complete' && result.info === 'OK') {
          placeSearch_CallBack(result);
        }
      });
      var infoWindow = new AMap.InfoWindow({
        autoMove: true,
        offset: {x: 0, y: -30}
      });

      //回调函数
      function placeSearch_CallBack(data) {
        // console.log(data)
        var poiArr = data.poiList.pois;
        //添加marker
        var marker = new AMap.Marker({
          map: map,
          position: poiArr[0].location,
          content:''
        });
        map.setCenter(marker.getPosition());
        infoWindow.setContent(createContent(poiArr[0]));
        infoWindow.open(map, marker.getPosition());
      }

      function createContent(poi) {  //信息窗体内容
        var s = [];
        s.push("<b>名称：" + poi.name + "</b>");
        s.push("地址：" + poi.address);
        s.push("电话：" + poi.tel);
        s.push("类型：" + poi.type);
        return s.join("<br>");
      }

    }
  })

  }




}
const searchNear = () => {
  AMap.plugin('AMap.PlaceSearch', function () {
    let map = new AMap.Map('container', {
      center: [116.857461, 38.310582], // 地图中心点坐标
      zoom: 15, // 地图缩放级别
      viewMode: '3D' // 使用3D视图'
      // pitch: 75, // 地图俯仰角度，默认0，取值范围0-83
    })
    var placeSearch = new AMap.PlaceSearch({
      // city 指定搜索所在城市，支持传入格式有：城市名、citycode和adcode
      city: '保定'
    })
    if (searchplace.value == '') {
      searchplace.value = '保定莲池区酒店'
    } else {
      searchplace.value = searchplace.value
    }
    //关键字查询


    placeSearch.search(searchplace.value, function (status, result) {


      // 查询成功时，result即对应匹配的POI信息
      // console.log(result)
      var pois = result.poiList.pois
      for (let i = 0; i < pois.length; i++) {
        var poi = pois[i]
        var marker = []
        marker[i] = new AMap.Marker({
          position: poi.location,   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
          title: poi.name
        })

        map.add(marker[i])
        marker[i].on('click', function (e) {
          searchlnt1.value = e.lnglat.getLat()
          searchlat1.value = e.lnglat.getLng()

          ss.value = e.target._originOpts.title

          setTimeout(() => {
            showPopup()
          }, 1000)
        })

      }


      map.setFitView()
    })

    var options = {
      'showButton': true,//是否显示定位按钮
      'position': 'LB',//定位按钮的位置
      /* LT LB RT RB */
      'offset': [10, 20],//定位按钮距离对应角落的距离
      'showMarker': true,//是否显示定位点
      'markerOptions': {//自定义定位点样式，同Marker的Options
        'offset': new AMap.Pixel(-18, -36),
        'content': '<img src="https://a.amap.com/jsapi_demos/static/resource/img/user.png" style="width:36px;height:36px"/>'
      },
      'showCircle': true,//是否显示定位精度圈
      'circleOptions': {//定位精度圈的样式
        'strokeColor': '#0093FF',
        'noSelect': true,
        'strokeOpacity': 0.5,
        'strokeWeight': 1,
        'fillColor': '#02B0FF',
        'fillOpacity': 0.25
      }
    }
    AMap.plugin('AMap.Geolocation', function () {
      var geolocation = new AMap.Geolocation(options)
      map.addControl(geolocation)
      geolocation.getCurrentPosition()
    })

  })

}


const startdaohang = () => {
  let map = new AMap.Map('container', {
    center: [116.857461, 38.310582], // 地图中心点坐标
    zoom: 15, // 地图缩放级别
    viewMode: '3D' // 使用3D视图'
    // pitch: 75, // 地图俯仰角度，默认0，取值范围0-83
  })

  AMap.plugin(["AMap.Driving", 'AMap.PlaceSearch'], function () {
    const driving = new AMap.Driving({
      map: map,
      panel: "panel",
    });

    var keywords = searchplace.value;
    AMap.plugin('AMap.PlaceSearch', function () {
      var autoOptions = {
        city: ''
      }
      var placeSearch = new AMap.PlaceSearch(autoOptions);
      placeSearch.search(keywords, function (status, result) {
        11
        // 搜索成功时，result即是对应的匹配数据
        // console.log(result)
        searchlnt.value = result.poiList.pois[0].location.lng
        searchlat.value = result.poiList.pois[0].location.lat
      })
    })
    if (searchlnt.value != '' || !searchlat.value != '') {
      const endLngLat = [searchlnt.value, searchlat.value]; //终点坐标
      const startLngLat = [Number(nownowplace.value.split(',')[0]), Number(nownowplace.value.split(',')[1])]; //起始点坐标
      // console.log(startLngLat,endLngLat)
      //   根据经纬度

      driving.search(startLngLat, endLngLat, function (status, result) {
        if (status === "complete") {
          //status：complete 表示查询成功，no_data 为查询无结果，error 代表查询错误
          //查询成功时，result 即为对应的驾车导航信息
          // console.log(result);
        } else {

          console.log("获取驾车数据失败：" + result);
        }
      });
    } else {
      // 使用地名确认起终点
      AMap.plugin('AMap.Geolocation', function () {
        var geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,//是否使用高精度定位，默认:true
          timeout: 10000,          //超过10秒后停止定位，默认：5s
          position: 'RB',    //定位按钮的停靠位置
          offset: [10, 20], //定位按钮与设置的停靠位置的偏移量，默认：[10, 20]
          zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点

        });
        map.addControl(geolocation);
        geolocation.getCurrentPosition(function (status, result) {
          // console.log(result)
        });
      });
      const points = [
        {keyword: "北京市地震局（公交站）", city: "北京"}, //起始点坐标
        {keyword: "亦庄文化园（地铁站）", city: "北京"}, //终点坐标
      ];
      // 根据地名
      driving.search(points, function (status, result) {
        if (status === "complete") {
          //status：complete 表示查询成功，no_data 为查询无结果，error 代表查询错误
          //查询成功时，result 即为对应的驾车导航信息
          // console.log(result);
        } else {
          console.log("获取驾车数据失败：" + result);
        }
      });

    }


  })
}

const ssdaohang = () => {
  show.value = false;
  let map = new AMap.Map('container', {
    center: [116.857461, 38.310582], // 地图中心点坐标
    zoom: 15, // 地图缩放级别
    viewMode: '3D' // 使用3D视图'
    // pitch: 75, // 地图俯仰角度，默认0，取值范围0-83
  })
  AMap.plugin('AMap.Driving', function () {
    var driving = new AMap.Driving({
      map: map,
      panel: 'panel1'
    })
    const endLngLat = [Number(searchlat1.value), Number(searchlnt1.value)]; //终点坐标
    const startLngLat = [Number(nownowplace.value.split(',')[0]), Number(nownowplace.value.split(',')[1])]; //起始点坐标
    // console.log('====================================');
    // console.log(endLngLat, startLngLat);
    // console.log('====================================');
    driving.search(startLngLat, endLngLat, function (status, result) {
      if (status === "complete") {
        //status：complete 表示查询成功，no_data 为查询无结果，error 代表查询错误
        //查询成功时，result 即为对应的驾车导航信息
        // console.log(result);
      } else {

        console.log("获取驾车数据失败：" + result);
      }
    });
  })
  // 使用坐标确认起终点

}
</script>


<style scoped>
#container {
  width: 100vw;
  height: 95vh;

}

#panel {
  position: absolute;
  font-size: 25rem;
}
</style>
